<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/style/admin.css" media="all">
    <link rel="stylesheet" href="/style/edit-table.css" media="all" />
</head>

<body>
    <div class="layui-fluid">
        <div class="layui-row layui-col-space15">
            <div class="layui-col-md12">
                <div class="layui-card">
                    <div class="layui-card-header">备件领用单</div>
                    <div class="layui-card-body">
                        <div style="margin-bottom: 10px;">
                            <div class="layui-input-item" style="float:left;padding-right:10px;">
                                <form class="layui-form layui-row layui-col-space16">
                                    <div class="layui-col-md6">
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">*领用人</label>
                                            <div class="layui-input-block">
                                                <select id="useBy" lay-search>
                                                    <option value="">选择领用人</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="layui-col-md6">
                                        <div class="layui-form-item">
                                            <label class="layui-form-label">领用原因</label>
                                            <div class="layui-input-block">
                                                <input type="text" id="purpose" placeholder="请输入领用原因"
                                                    class="layui-input">
                                            </div>
                                        </div>
                                    </div>

                                </form>
                            </div>

                            <div style="clear:both;"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-row layui-col-space15">
            <div class="layui-col-md12">
                <div class="layui-card">
                    <div class="layui-card-header">领用出库单明细</div>
                    <div class="layui-card-body">
                        <div style="margin-bottom: 10px;">
                            <div>
                                <a id="add-btn" class="layui-btn">添加</a>
                                <a id="del-btn" class="layui-btn  layui-btn-danger">删除</a>
                                <a id="clear-btn" class="layui-btn layui-btn-primary">清空</a>
                            </div>
                            <div style="clear:both;"></div>
                        </div>
                        <table class="layui-hide" id="item-table" lay-filter="item-table"></table>
                    </div>
                </div>
            </div>
        </div>
        <div style="text-align: center;padding: 20px;">
            <a id="submit-btn" class="layui-btn">提交单据</a>
            <a id="save-btn" class="layui-btn layui-btn-primary">保存草稿</a>
            <a id="back-btn" class="layui-btn layui-btn-primary">返回</a>
        </div>

    </div>

    <script type="text/html" id="sparepart-tpl">
    <div class="layui-form">
        {{# }}
        <select lay-filter="sparepart" lay-search>
            <option value="">选择备品备件</option>
            {{# layui.each(groupedSpareparts, function(group, items){ }}
            <optgroup label="{{=group}}">
                {{# layui.each(items, function(i, v){ }}
                <option value="{{= v.id }}" {{=v.id
                == d.sparepartId ? 'selected' : '' }} {{=v.disabled ? 'disabled' : '' }} >{{= v.name }} | {{= v.brand }}
                |
                {{= v.model }}</option>
                {{# }); }}
            </optgroup>
            {{# }); }}
        </select>
    </div>
</script>
    <script type="text/html" id="quantity-tpl">
    <input type="number" class="layui-input quantity" min="0" value="{{= d.quantity}}" lay-verify="required">
</script>
    <script type="text/html" id="note-tpl">
    <input type="text" class="layui-input note" value="{{= d.note}}">
</script>

    <script src="/layui/layui.js"></script>
    <script>
        var spareparts = [];//备件清单
        var groupedSpareparts = {};//分组后的备件清单
        var sparepartMap;//备件清单hash表（根据ID快速查找）
        //业务单据健名
        const ORDER_KEY = 'sparepart-use-order';
        layui.config({
            base: '/' //静态资源所在路径
        }).extend({
            index: 'lib/index' //主入口模块
        }).use(['index', 'table', 'form', 'laydate'], function () {
            var $ = layui.$;
            var table = layui.table;
            var form = layui.form;

            //加载初始单据
            var orderData = JSON.parse(sessionStorage.getItem(ORDER_KEY) || '{}');
            //初始化单头
            $('#useBy').val(orderData.useBy);//领用人
            $('#purpose').val(orderData.purpose);//领用原因

            //加载备件库
            loadSpareparts(function (data) {
                spareparts = data;
                groupedSpareparts = spareparts.reduce((groups, sparepart) => {
                    if (!groups[sparepart.typeText]) {
                        groups[sparepart.typeText] = [];
                    }
                    groups[sparepart.typeText].push(sparepart);
                    return groups;
                }, {});
                sparepartMap = new Map(spareparts.map(item => [item.id, item]));
                //已在明细中的禁用
                if (orderData.items) {
                    let sparepartIds = new Set(orderData.items.map(item => item.sparepartId));
                    for (let sparepart of spareparts) {
                        if (sparepartIds.has(sparepart.id)) {
                            sparepart['disabled'] = true;
                        }
                    }
                }
            });

            function loadSpareparts(callback) {
                $.ajax({
                    url: '/spareparts', // 你的请求URL
                    type: 'GET',
                    async: false, // 设置为同步请求
                    success: function (result) {
                        if (callback) {
                            callback(result.data);
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error(error);
                    }
                });
            }

            loadUsers(function (result) {
                for (var i in result) {
                    var item = result[i];
                    $('#useBy').append('<option value="' + item.name + '">' + item.name + '</option>');
                }
                form.render();
            });

            /**
                    * 加载角色
                    * @param callback
                    */
            function loadUsers(callback) {
                $.get('users', function (result) {
                    if (callback) {
                        callback(result.data);
                    }
                });
            }

            table.render({
                elem: '#item-table',
                data: orderData.items || [{}],
                cols: [[
                    { checkbox: true, fixed: true },
                    { field: 'sparepartId', title: '选择备品备件', width: 420, templet: '#sparepart-tpl' },
                    { field: 'name', width: 200, title: '备件名称' },
                    { field: 'brand', width: 150, title: '品牌' },
                    { field: 'model', width: 150, title: '型号/规格' },
                    { field: 'unit', width: 100, title: '单位', align: 'center' },
                    { field: 'quantity', width: 100, title: '数量', templet: '#quantity-tpl' },
                    { field: 'note', title: '备注', templet: '#note-tpl' }
                ]],
                done: function (res, curr, count) {
                    let options = this;
                    let tableId = options.id;
                    // 获取表格所有数据
                    table.getTableData = function () {
                        return table.cache[tableId];
                    };
                    // 获取当前行数据
                    table.getRowData = function (elem) {
                        let index = $(elem).closest('tr').data('index');
                        return table.cache[tableId][index] || {};
                    };
                    //将组件的值设置到数据模型
                    table.setRowFieldValue = function (elem, field) {
                        let value = elem.val(); // 获取输入框的值
                        let rowData = table.getRowData(elem);
                        rowData[field] = value;
                    }
                    //添加一行
                    table.addRow = function () {
                        let tableData = table.getTableData();
                        tableData.push({});
                        table.reloadData();
                    }
                    // 获取表格选中数据
                    table.getCheckedData = function () {
                        let checkStatus = table.checkStatus(tableId);
                        return checkStatus.data;
                    };
                    // 重新加载数据
                    table.reloadData = function (data) {
                        table.reload(tableId, {
                            data: data ? data : table.cache[tableId],
                        }, function (res) {
                            console.error(res);
                        });
                    };

                    //备品备件选择监听
                    form.on('select(sparepart)', function (data) {
                        let elem = data.elem; // 获得 select 原始 DOM 对象
                        let value = data.value; // 获得被选中的值
                        let rowData = table.getRowData(elem); // 获取当前行数据(如 id 等字段，以作为数据修改的索引)
                        let preSparepartId = rowData['sparepartId'];//更改前的值
                        let preSparepart = sparepartMap.get(preSparepartId);
                        let sparepartId = parseInt(value);
                        rowData['sparepartId'] = sparepartId;
                        let sparepart = sparepartMap.get(sparepartId);
                        rowData['name'] = sparepart['name'];
                        rowData['brand'] = sparepart['brand'];
                        rowData['model'] = sparepart['model'];
                        rowData['unit'] = sparepart['unit'];
                        sparepart['disabled'] = true;
                        if (preSparepart) {
                            delete preSparepart['disabled'];
                        }
                        table.reload(tableId);
                    });
                    //数量
                    $('.quantity').on('blur', function () {
                        table.setRowFieldValue($(this), 'quantity');
                    });
                    //备注
                    $('.note').on('blur', function () {
                        table.setRowFieldValue($(this), 'note');
                    });
                }
            });

            table.render({
                elem: '#user-table',
                url: 'users',
                title: '',
                skin: 'line',
                cols: [[
                    { type: 'checkbox' },
                    { field: 'name', title: '姓名' },
                    { field: 'code', title: '编码' },
                    { field: 'account', title: '账号' },
                    { field: 'mobile', title: '手机号' },
                    { field: 'roleNames', title: '角色' },
                    { field: 'syncText', title: '同步状态' },
                    { field: 'isEnabled', title: '启用状态', width: 150, templet: '#stateTpl' },
                    { fixed: 'right', title: '操作', width: 320, align: 'center', toolbar: '#toolbar-operation' }
                ]],
                page: true
            });

            //添加明细
            $("#add-btn").on('click', function () {
                let tableData = table.getTableData();   //获取当前表格中数据
                let lastRow = tableData[tableData.length - 1];
                if (!lastRow.sparepartId) {
                    layer.msg('请先完成当前行');
                    return;
                }
                tableData.push({});
                table.reloadData();
            });

            //删除选中明细
            $("#del-btn").on('click', function () {
                let checkedData = table.getCheckedData();
                let tableData = table.getTableData();
                let sparepartIds = new Set(checkedData.map(item => item.sparepartId));
                for (let i = tableData.length - 1; i >= 0; i--) {
                    if (tableData[i].sparepartId && sparepartIds.has(tableData[i].sparepartId)) {
                        let sparepart = sparepartMap.get(tableData[i].sparepartId);
                        delete sparepart['disabled'];
                        tableData.splice(i, 1);
                    }
                }
                table.reloadData();
            });

            //清空明细
            $("#clear-btn").on('click', function () {
                layer.confirm('确定清空明细吗？', function (index) {
                    clearItems();
                    layer.close(index);
                });
            });

            $("#submit-btn").on('click', function () {
                let orderData = getOrderData();
                // console.log('orderData',orderData);

                if (checkOrderData(orderData)) {
                    $.ajax({
                        url: '/sparepart-use-orders',
                        type: 'PUT',
                        contentType: 'application/json',
                        data: JSON.stringify(orderData),
                        dataType: 'json', // 期望从服务器返回的数据类型
                        success: function (res) {
                            console.log(res);
                            if (res.code == 200) {
                                sessionStorage.removeItem(ORDER_KEY);
                                $('#useBy').empty();
                                form.render('select');
                                $('#purpose').val('');
                                clearItems();
                                layer.msg('单据已提交');
                            } else {
                                layer.msg(res.msg);
                            }
                        },
                        error: function (xhr, status, error) {
                            console.error('Error:', error);
                        }
                    });
                }
            });

            $("#save-btn").on('click', function () {
                let orderData = getOrderData();
                sessionStorage.setItem(ORDER_KEY, JSON.stringify(orderData));
                layer.msg('单据已暂存');
            });

            $("#back-btn").on('click', function () {
                window.location.href = 'sparepart-use-order.html';
            });

            /**
             * 清空明细
             */
            function clearItems() {
                for (let sparepart of spareparts) {
                    delete sparepart['disabled'];
                }
                table.reloadData([{}]);
            }

            /**
             * 获取单据数据
             * @returns {{}}
             */
            function getOrderData() {
                let orderData = {};
                let tableData = table.getTableData();
                let items = [];
                for (let data of tableData) {
                    let item = Object.assign({}, data);
                    delete item['LAY_TABLE_INDEX'];
                    items.push(item);
                }
                orderData.items = items;
                orderData.useBy = $('#useBy').val();
                orderData.purpose = $('#purpose').val();
                return orderData;
            }

            /**
             * 检查单据数据合法性
             * @param orderData
             * @returns {boolean}
             */
            function checkOrderData(orderData) {
                let items = orderData.items;
                // console.log(items);
                
                for (let item of items) {
                    if (!orderData.useBy) {
                        layer.msg('请添加领用人');
                        return false;
                    }
                    if (!item.sparepartId) {
                        layer.msg('请选择备件');
                        return false;
                    }
                    if (!item.quantity) {
                        layer.msg('请填写数量');
                        return false;
                    }
                }
                return true;
            }
        });
    </script>
</body>

</html>